package com.health.activity.settings;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.UPDataMenuGridAdapter;
import com.health.db.FDbManager;
import com.health.model.UpDataReturn;
import com.health.tablebean.JTYSCustomerDoctorCont;
import com.health.tablebean.JTYSDoctorEvaluateBean;
import com.health.tablebean.JTYS_BASEINFO;
import com.health.tablebean.webservice.ChildWithOneYearOld;
import com.health.tablebean.webservice.ChildhealthNeonate;
import com.health.tablebean.webservice.Diabetes;
import com.health.tablebean.webservice.HdPersonalInfo;
import com.health.tablebean.webservice.HealthCheck;
import com.health.tablebean.webservice.Hypertensio;
import com.health.tablebean.webservice.MeasurementData;
import com.health.tablebean.webservice.OldPhysique;
import com.health.tablebean.webservice.OldSelfHelp;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.JX_FWXMB;
import com.health.tools.JX_SJSC;
import com.health.tools.JX_UploadData;
import com.health.tools.ResultTextDialog;
import com.health.tools.SPUtil;
import com.health.tools.UploadDataBean;
import com.health.tools.UploadDatas;
import com.health.tools.WebService;
import com.health.webservices.WebServiceConts;
import com.health.webservices.ZCMWebService;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 数据下载
 */
public class DataDownLoadMainActivity extends NovaActivity implements OnClickListener {
    private static final String TAG = "DataDownLoadMainActivity";
    private static final int DOWNLOAD_OVER = 1;
    private static final int UPLOAD_FWMYD = 2;
    private static final int NO_DATA = 3;
    private static final int SHOW_UPLOAD_RESULT = 4;
    private static final int UPLOAD_FUMYD2 = 5;
    private static final int UPDATA_TNB = 8;
    private static final int UPDATA_GXY = 9;
    protected static final int UPDATA_JKTJ = 10;
    protected static final int UPDATA_OLDZY = 11;
    protected static final int UPDATA_OLDZL = 12;
    protected static final int UPLOAD_MEASUREMENT_DATA = 13;
    protected static final String TYPE_FWXMB = "TYPE_FWXMB";
    protected static final String TYPE_JTQYYH = "TYPE_JTQYYH";
    public static final String TYPE_FWMYDPJ = "TYPE_FWMYDPJ";
    public static final String TYPE_CJYH = "TYPE_CJYH";
    private GridView gd_menu;
    private UPDataMenuGridAdapter menuAdapter;
    private TextView title;
    private Button btn_back;
    private Button btn_up;
    private ImageView img_photo;
    private TextView tv_name;
    static FDbManager fdbmanager = null;
    private int sumSize = 0;
    private int successCount = 0;
    private int failCount = 0;
    private int sumSize0 = 0;
    private int successCount0 = 0;
    private int failCount0 = 0;
    private String errorMsg0 = "";
    private int failCountYcz0 = 0;
    private int sumSize1 = 0;
    private int successCount1 = 0;
    private int failCount1 = 0;
    private int sumSize2 = 0;
    private int successCount2 = 0;
    private int failCount2 = 0;
    private int sumSize3 = 0;
    private int successCount3 = 0;
    private int failCount3 = 0;
    boolean isWorking = true;
    private String upType = "";
    private ResultTextDialog resultDialog;
    private GridView gd_menu1;
    private ImageView img_photo1;
    private TextView tv_name1;
    private UPDataMenuGridAdapter menuAdapter1;
    // private final int SUCCESS = 1;
    // private final int FALSE = 2;
    // private final int NODATE = 3;
    // private int personinfo = 0;//1 成功 2 失败 3 无数据
    // private int GXY = 0;//1 成功 2 失败 3 无数据
    // private int TNB = 0;//1 成功 2 失败 3 无数据
    // private boolean isUploadNationalPublic = false;
    // List<Diabetes> convertDiabetesData = null;// =
    // // Diabetes.convertData(DataDownLoadMainActivity.this);
    // List<HdPersonalInfo> convertHdPersonalInfoData = null;// =
    // // HdPersonalInfo.convertData(DataDownLoadMainActivity.this);
    // List<Hypertensio> convertHypertensioData = null;// =
    // // Hypertensio.convertData(DataDownLoadMainActivity.this);
    // List<HealthCheck> convertHealthCheckData = null;
    // List<OldPhysique> convertOldPhysiqueData = null;
    // List<OldSelfHelp> convertOldSelfHelpData = null;

    List<HdPersonalInfo> convertDataInfo;//个人基本信息
    List<Diabetes> convertDataTnb;//糖尿病
    List<Hypertensio> convertDataGxy;//高血压
    List<HealthCheck> convertDataJktj;//健康体检
    List<OldPhysique> convertDataLnrzyy;//老年人中医药
    List<OldSelfHelp> convertDataLnrzlnl;//老年人自理能力
    List<JTYSCustomerDoctorCont> conts;//签约用户
    List<JTYSDoctorEvaluateBean> evaluates;//用户满意度
    List<ChildhealthNeonate> convertDataXSRFS;//新生儿访视
    List<ChildWithOneYearOld> convertDataOneMonth;//满月内检查
    List<ChildWithOneYearOld> convertDataThreeMonth;//三月龄
    List<ChildWithOneYearOld> convertDataSixMonth;//六月龄
    List<ChildWithOneYearOld> convertData8Month;//八月龄



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.jkjy_main_content_modify);
        fdbmanager = NovaApplication.fdbmanger;
        findViews();
        addListeners();
    }

    @Override
    public void findViews() {
        gd_menu = (GridView) findViewById(R.id.gd_menu);
        title = (TextView) findViewById(R.id.title);
        title.setText("同步数据");

        img_photo = (ImageView) findViewById(R.id.img_photo);
        img_photo.setImageResource(R.drawable.downl_s);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setText("数据下载");
        menuAdapter = new UPDataMenuGridAdapter(this, GlobalContsJTYS.MENU_DOWNLOAD);
        gd_menu.setAdapter(menuAdapter);
        btn_back = (Button) findViewById(R.id.btn_back);

        btn_up = (Button) findViewById(R.id.btn_up);
        btn_up.setVisibility(View.GONE);

        gd_menu1 = (GridView) findViewById(R.id.gd_menu1);
        menuAdapter1 = new UPDataMenuGridAdapter(this, GlobalContsJTYS.MENU_UPLOAD);
        gd_menu1.setAdapter(menuAdapter1);
        img_photo1 = (ImageView) findViewById(R.id.img_photo1);
        img_photo1.setImageResource(R.drawable.upload_s);
        tv_name1 = (TextView) findViewById(R.id.tv_name1);
        tv_name1.setText("数据上传");
        System.out.println("");
    }

    public void addListeners() {
        btn_back.setOnClickListener(this);
        // 菜单选项
        gd_menu.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if
                        (!GlobalConts.isNetworkAvailable(DataDownLoadMainActivity.this)) {
                    showTextDialog("请先检查网络");
                    return;
                }

//				 if (resultDialog == null) {
//				 resultDialog = new
//				 ResultTextDialog(DataDownLoadMainActivity.this);
//				 }
//				 cleanData();
//				 String result_type = "";
//				 if (position == 0) {
//				 // 基础情况填报表
//				 upType = TYPE_FWXMB;
//				 result_type = "服务项目包";
//
//				 } else if (position == 1) {
//				 // 下载家庭签约用户（废弃）
//				 upType = TYPE_JTQYYH;
//				 result_type = "家庭签约用户";
//
//				 }
//				 resultDialog.setText(result_type + "数据正在下载中，请稍后...");
//				 resultDialog.show();
//
//				 new Thread(runnable).start();// 线程启动
                CheckToken();
                if (resultDialog == null) {
                    resultDialog = new ResultTextDialog(DataDownLoadMainActivity.this);
                }
                resultDialog.show("数据正在下载中，请稍候...");

                downloadFWXMB();

            }

            /**
             * 服务项目包下载
             */
            private void downloadFWXMB() {
                try {
                    WebService webService = new WebService(mContext) {
                        @Override
                        public void start(String message) {
                            super.start(message);// 开始 46fas
                            System.out.println("start::" + message);
                            Log.e("start-------", message);
                        }

                        @Override
                        public void complete(String message) {
                            super.complete(message);
                            System.out.println("complete::" + message);
                            cleanData();
                            if (!TextUtils.isEmpty(message)) {
                                UpDataReturn up = JX_FWXMB.jxFwxmbData(message.toString());
                                if (up != null) {
                                    if (up.getSize() > 0) {
                                        sumSize = up.getSize();
                                        successCount = up.getSuccessCount();
                                        failCount = up.getFailCount();
                                    } else {
                                        cleanData();
                                    }
                                } else {
                                    cleanData();
                                }
                            }
                            mHandler.sendEmptyMessage(DOWNLOAD_OVER);

                        }

                        public void onError(String message) {
                            Log.e("tag", message);
                            mHandler.sendEmptyMessage(DOWNLOAD_OVER);
                        }

                        ;
                    };
                    HashMap<String, Object> params = new HashMap<String, Object>();
                    // params.put("type", "1");
                    params.put("organcode", NovaApplication.getJgbh());

                    webService.downloaddata(GlobalConts.getUrlPost() + WebServiceConts.WEBSERVICE_URL_FWXMB,
                            WebServiceConts.WEBSERVICE_URL_FWXMB_METHODNAME,
                            WebServiceConts.WEBSERVICE_URL_XZQ_NAMESPACE, null, params, "listdoctorPad");

                } catch (Exception e) {
                    mHandler.sendEmptyMessage(DOWNLOAD_OVER);
                }
            }
        });

        gd_menu1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!GlobalConts.isNetworkAvailable(DataDownLoadMainActivity.this)) {
                    showTextDialog("请先检查网络");
                    return;
                }
                cleanData();
                if (resultDialog == null) {
                    resultDialog = new ResultTextDialog(DataDownLoadMainActivity.this);
                }
                String result_type = "";
                CheckToken();
                if (position == 1) {
//                    List list = new ArrayList<>();
                    conts = NovaApplication.fdbmanger.findAllByWhere(
                            JTYSCustomerDoctorCont.class,
                            "CREATER='" + NovaApplication.getJgrUserLoginName() + "' AND SIGN!='1'");

                    evaluates = NovaApplication.fdbmanger.findAllByWhere(
                            JTYSDoctorEvaluateBean.class,
                            "CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");
                    handler.sendEmptyMessage(2);
//                    if (conts != null && conts.size() > 0) {
//                        // 签约用户数据上传
//                        UploadDataBean udb1 = new UploadDataBean("签约用户", JX_UploadData.TYPE_QYYH, "jsonQYStr",
//                                "addCustomerDoctorCont", "", conts);
//                        list.add(udb1);
//                    }

//                    if (evaluates != null && evaluates.size() > 0) {
//                        // 服务满意度用户数据上传
//                        UploadDataBean udb2 = new UploadDataBean("服务满意度用户", JX_UploadData.TYPE_FWMYD, "ServiceSatisJson",
//                                "addServiceSatis", "", evaluates);
//                        list.add(udb2);
//                    }
//                    UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
//                    uld.uploadDatas();
                    return;

                    // result_type = "签约用户";
                    // resultDialog.setText(result_type + "数据正在上传中，请稍候...");
                    // resultDialog.show();
                    // Log.e("tag", "OnItemClickListener+++++");
                    // getDataUp();
                    // }

                } else if (position == 0) {


                    convertDataInfo = HdPersonalInfo.convertData(DataDownLoadMainActivity.this);
                    convertDataTnb =
                            Diabetes.convertData(DataDownLoadMainActivity.this);
                    convertDataGxy =
                            Hypertensio.convertData(DataDownLoadMainActivity.this);
                    convertDataJktj =
                            HealthCheck.convertData(DataDownLoadMainActivity.this);
                    convertDataLnrzyy =
                            OldPhysique.convertData(DataDownLoadMainActivity.this);
                    convertDataLnrzlnl =
                            OldSelfHelp.convertData(DataDownLoadMainActivity.this);
                    convertDataXSRFS =
                            ChildhealthNeonate.convertData(DataDownLoadMainActivity.this);
                    convertDataOneMonth =
                            ChildWithOneYearOld.convertData(DataDownLoadMainActivity.this, "1");
                    convertDataThreeMonth =
                            ChildWithOneYearOld.convertData(DataDownLoadMainActivity.this, "2");
                    convertDataSixMonth =
                            ChildWithOneYearOld.convertData(DataDownLoadMainActivity.this, "3");
                    convertData8Month =
                            ChildWithOneYearOld.convertData(DataDownLoadMainActivity.this, "4");

                    handler.sendEmptyMessage(1);

//                    if (convertDataTnb != null && convertDataTnb.size() > 0) {
//                        // 糖尿病
//                        UploadDataBean udb2 = new UploadDataBean("糖尿病",
//                                JX_UploadData.TYPE_DIABETES, "TnbJson",
//                                "addTnb", "tnb", convertDataTnb);
//                        list.add(udb2);
//                    }
//

//                    if (convertDataGxy != null && convertDataGxy.size() > 0) {
//                        // 高血压
//                        UploadDataBean udb3 = new UploadDataBean("高血压",
//                                JX_UploadData.TYPE_HYPERTENSION, "HyperJson",
//                                "addHypertension", "gxy", convertDataGxy);
//                        list.add(udb3);
//                    }
//

//                    if (convertDataJktj != null && convertDataJktj.size() >
//                            0) {
//                        // 健康体检
//                        UploadDataBean udb4 = new UploadDataBean("健康体检",
//                                JX_UploadData.TYPE_HEALTHCHECK, "JktjAllJson",
//                                "addJktjAll", "jktj", convertDataJktj);
//                        list.add(udb4);
//                    }
//
//
//                    if (convertDataLnrzyy != null && convertDataLnrzyy.size()
//                            > 0) {
//                        // 老年人中医药
//                        UploadDataBean udb5 = new UploadDataBean("老年人中医药",
//                                JX_UploadData.TYPE_OLD_PHYSIQUE,
//                                "OldPhysiqueJson", "addOldPhysique", "oldPhysic",
//                                convertDataLnrzyy);
//                        list.add(udb5);
//                    }
//
//
//                    if (convertDataLnrzlnl != null &&
//                            convertDataLnrzlnl.size() > 0) {
//                        // 老年人自理能力
//                        UploadDataBean udb6 = new UploadDataBean("老年人自理能力",
//                                JX_UploadData.TYPE_OLD_SELF_HELP,
//                                "OlsSelfHelpJson", "addOldSelfHelp", "oldself",
//                                convertDataLnrzlnl);
//                        list.add(udb6);
//                    }

//					 List<ChildhealthNeonate> convertDataXSRFS =
//							 ChildhealthNeonate.convertData(DataDownLoadMainActivity.this);
//					 if (convertDataXSRFS != null &&
//							 convertDataXSRFS.size() > 0) {
//					 // 新生儿访视
//					 UploadDataBean udb10 = new UploadDataBean("新生儿访视",
//					 JX_UploadData.TYPE_XSRFS,
//					 "jsonkey", "addChildhealthNeonate", "",
//							 convertDataXSRFS);
//					 list.add(udb10);
//					 }
//
//
//                    List<ChildWithOneYearOld> convertDataOneMonth =
//                            ChildWithOneYearOld.convertData(DataDownLoadMainActivity.this,"1");
//                    if (convertDataOneMonth != null &&
//                            convertDataOneMonth.size() > 0) {
//                        // 满月内检查
//                        UploadDataBean udb11 = new UploadDataBean("满月龄儿童访视",
//                                JX_UploadData.TYPE_XSRFS,
//                                "jsonkey", "addChildhealthChildren", "",
//                                convertDataOneMonth);
//                        list.add(udb11);
//                    }
//
//
//                    if (convertDataThreeMonth != null &&
//                            convertDataThreeMonth.size() > 0) {
//                        // 三月内检查
//                        UploadDataBean udb12 = new UploadDataBean("三月龄儿童访视",
//                                JX_UploadData.TYPE_THREEMONTH,
//                                "jsonkey", "addChildhealthChildren", "",
//                                convertDataThreeMonth);
//                        list.add(udb12);
//                    }
//
//
//                    if (convertDataSixMonth != null &&
//                            convertDataSixMonth.size() > 0) {
//                        // 六月内检查
//                        UploadDataBean udb12 = new UploadDataBean("六月龄儿童访视",
//                                JX_UploadData.TYPE_SIXMONTH,
//                                "jsonkey", "addChildhealthChildren", "",
//                                convertDataSixMonth);
//                        list.add(udb12);
//                    }

//
//                    if (convertData8Month != null &&
//                            convertData8Month.size() > 0) {
//                        // 8月内检查
//                        UploadDataBean udb12 = new UploadDataBean("8月龄儿童访视",
//                                JX_UploadData.TYPE_EIGHTMONTH,
//                                "jsonkey", "addChildhealthChildren", "",
//                                convertData8Month);
//                        list.add(udb12);
//                    }


//					List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(
//							JTYSCustomerDoctorCont.class,
//							"CREATER='" + SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this) + "' AND SIGN!='1'");
//					if (conts != null && conts.size() > 0) {
//						// 签约用户数据上传
//						UploadDataBean udb7= new UploadDataBean("签约用户", JX_UploadData.TYPE_QYYH, "jsonkey",
//								"addCustomerDoctorCont", "", conts);
//						list.add(udb7);
//					}
//
//					List<JTYSDoctorEvaluateBean> evaluates = NovaApplication.fdbmanger.findAllByWhere(
//							JTYSDoctorEvaluateBean.class,
//							"CREATER='" + SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this) + "' AND SIGN ='0'");
//					if (evaluates != null && evaluates.size() > 0) {
//						// 服务满意度用户数据上传
//						UploadDataBean udb8 = new UploadDataBean("服务满意度用户", JX_UploadData.TYPE_FWMYD, "ServiceSatisJson",
//								"addServiceSatis", "", evaluates);
//						list.add(udb8);
//					}
//
//					List<JTYS_SignPictureData> pictures  = NovaApplication.fdbmanger.findAllByWhere(JTYS_SignPictureData.class,
//							"createrId='" + SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this) + // "'");
//									"' AND isUpdate ='Y'");
//
//					if (pictures != null && pictures.size() > 0) {
//						// 照片数据上传
//						UploadDataBean udb9 = new UploadDataBean("照片", JX_UploadData.TYPE_PICTURE, "json",
//								"uploadFile", "", pictures);
//						list.add(udb9);
//					}


                    return;
                }
            }

        });
    }

    int s = 0;
    int f = 0;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 11:
                    String count = (String) msg.getData().get("count");
                    String[] counts = count.split("/");
                    s = s + Integer.parseInt(counts[0]);
                    f = f + Integer.parseInt(counts[1]);
                    String name = counts[2];

                    if ("个人基本信息".equals(name)) {
                        if (convertDataInfo != null && convertDataInfo.size() > 0) {
                            upDataJBXX();
                        } else {
                            successUd(name);
                            if (convertDataTnb != null && convertDataTnb.size() > 0) {
                                upDataTNB();
                            } else if (convertDataGxy != null && convertDataGxy.size() > 0) {
                                updateGXY();

                            } else if (convertDataJktj != null && convertDataJktj.size() > 0) {
                                updaTaJKTJ();
                            } else if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                                upDataLNRZYY();
                            } else if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                                upDataLNRZLNL();
                            } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("糖尿病".equals(name)) {
                        if (convertDataTnb != null && convertDataTnb.size() > 0) {
                            upDataTNB();
                        } else {
                            successUd(name);
                            if (convertDataGxy != null && convertDataGxy.size() > 0) {
                                updateGXY();

                            } else if (convertDataJktj != null && convertDataJktj.size() > 0) {
                                updaTaJKTJ();
                            } else if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                                upDataLNRZYY();
                            } else if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                                upDataLNRZLNL();
                            } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("高血压".equals(name)) {
                        if (convertDataGxy != null && convertDataGxy.size() > 0) {
                            updateGXY();
                        } else {
                            successUd(name);
                            if (convertDataJktj != null && convertDataJktj.size() > 0) {
                                updaTaJKTJ();
                            } else if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                                upDataLNRZYY();
                            } else if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                                upDataLNRZLNL();
                            } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("健康体检".equals(name)) {
                        if (convertDataJktj != null && convertDataJktj.size() > 0) {
                            updaTaJKTJ();
                        } else {
                            successUd(name);
                            if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                                upDataLNRZYY();
                            } else if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                                upDataLNRZLNL();
                            } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("老年人中医药".equals(name)) {
                        if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                            upDataLNRZYY();
                        } else {
                            successUd(name);
                            if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                                upDataLNRZLNL();
                            } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("老年人自理能力".equals(name)) {
                        if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                            upDataLNRZLNL();
                        } else {
                            successUd(name);
                            if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                                upDataXSEFS();
                            } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("新生儿访视".equals(name)) {
                        if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                            upDataXSEFS();
                        } else {
                            successUd(name);
                            if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                                upDataMYLET();
                            } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("满月龄儿童访视".equals(name)) {
                        if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                            upDataMYLET();
                        } else {
                            successUd(name);
                            if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                                upDataSYLET();
                            } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("三月龄儿童访视".equals(name)) {
                        if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                            upDataSYLET();
                        } else {
                            successUd(name);
                            if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                                upDataLYLET();
                            } else if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }
                        }
                    } else if ("六月龄儿童访视".equals(name)) {
                        if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                            upDataLYLET();
                        } else {
                            successUd(name);
                            if (convertData8Month != null && convertData8Month.size() > 0) {
                                upDataBYLET();
                            }

                        }
                    } else if ("8月龄儿童访视".equals(name)) {
                        if (convertData8Month != null && convertData8Month.size() > 0) {
                            upDataBYLET();
                        } else {
                            successUd(name);

                        }
                    }

                    if ("签约用户".equals(name)) {
                        if (conts != null && conts.size() > 0) {
                            upDataQYYH();
                        } else {
                            successUd(name);
                            if (evaluates != null && evaluates.size() > 0) {
                                upDataFWMYD();
                            }
                        }
                    } else if ("服务满意度用户".equals(name)) {
                        if (evaluates != null && evaluates.size() > 0) {
                            upDataFWMYD();
                        } else {
                            successUd(name);
//                            if (evaluates != null && evaluates.size() > 0) {
//                                upDataFWMYD();
//                            }
                        }
                    }


                    break;
                case 1:
                    if (convertDataInfo.size() == 0 && convertDataTnb.size() == 0 && convertDataGxy.size() == 0 && convertDataJktj.size() == 0 && convertDataLnrzyy.size() == 0 && convertDataLnrzlnl.size() == 0 && convertDataXSRFS.size() == 0) {
                        showTextDialog("无数据可上传");
                        return;
                    }


                    if (convertDataInfo != null && convertDataInfo.size() > 0) {
                        upDataJBXX();
                    } else if (convertDataTnb != null && convertDataTnb.size() > 0) {
                        upDataTNB();
                    } else if (convertDataGxy != null && convertDataGxy.size() > 0) {
                        updateGXY();
                    } else if (convertDataJktj != null && convertDataJktj.size() > 0) {
                        updaTaJKTJ();
                    } else if (convertDataLnrzyy != null && convertDataLnrzyy.size() > 0) {
                        upDataLNRZYY();
                    } else if (convertDataLnrzlnl != null && convertDataLnrzlnl.size() > 0) {
                        upDataLNRZLNL();
                    } else if (convertDataXSRFS != null && convertDataXSRFS.size() > 0) {
                        upDataXSEFS();
                    } else if (convertDataOneMonth != null && convertDataOneMonth.size() > 0) {
                        upDataMYLET();
                    } else if (convertDataThreeMonth != null && convertDataThreeMonth.size() > 0) {
                        upDataSYLET();
                    } else if (convertDataSixMonth != null && convertDataSixMonth.size() > 0) {
                        upDataLYLET();
                    } else if (convertData8Month != null && convertData8Month.size() > 0) {
                        upDataBYLET();
                    }


                    break;
                case 2:
                    if (conts.size() == 0 && evaluates.size() == 0) {
                        showTextDialog("无数据可上传");
                        return;
                    }
                    if (conts != null && conts.size() > 0) {
                        upDataQYYH();
                    } else if (evaluates != null && evaluates.size() > 0) {
                        upDataFWMYD();
                    }

                    break;
            }
        }
    };

    public void successUd(String name) {
        cancelProgressDialog();
        showTextDialog(name + "上传完成," + "  成功：" + s + "  失败：" + f);
        Log.e("**********", "上传完成" + "成功：" + s + "失败：" + f);
        s = 0;
        f = 0;


    }


    private void wait(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 基本信息
     */
    public void upDataJBXX() {
        List list = new ArrayList<>();
        // 个人基本信息
        List<HdPersonalInfo> newList = null;

        if (convertDataInfo.size() > 10) {
            newList = convertDataInfo.subList(0, 10);
            convertDataInfo = convertDataInfo.subList(10, convertDataInfo.size());
            Log.e("*************", newList.size() + "***" + convertDataInfo.size() + "*******************");
        } else {
            newList = convertDataInfo;
            convertDataInfo = null;
        }
        for (int i = 0; i < newList.size(); i++) {
            if (TextUtils.isEmpty(newList.get(i).getModified())) {
                newList.get(i).setModified(newList.get(i).getCreater());
            }
        }
        UploadDataBean udb1 = new UploadDataBean("个人基本信息", JX_UploadData.TYPE_PERSONALINFO, "jsonStr",
                "addHdPersonalInfo", "grjbxx", newList);
        list.add(udb1);
        showProgressDialog(udb1.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 糖尿病
     */
    public void upDataTNB() {
        List list = new ArrayList<>();
        // 糖尿病
        List<Diabetes> newList = null;

        if (convertDataTnb.size() > 10) {
            newList = convertDataTnb.subList(0, 10);
            convertDataTnb = convertDataTnb.subList(10, convertDataTnb.size());
            Log.e("*************", newList.size() + "***" + convertDataTnb.size() + "*******************");
        } else {
            newList = convertDataTnb;
            convertDataTnb = null;
        }

        UploadDataBean udb2 = new UploadDataBean("糖尿病",
                JX_UploadData.TYPE_DIABETES, "TnbJson",
                "addTnb", "tnb", newList);
        list.add(udb2);
        showProgressDialog(udb2.getDataName() + "数据正在上传中，请稍候...");
        GlobalConts.UPLOAD_TYPE = "/CD_DIABETESFOLLOWUP";
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 高血压
     */
    public void updateGXY() {
        List list = new ArrayList<>();
        // 高血压
        List<Hypertensio> newList = null;

        if (convertDataGxy.size() > 10) {
            newList = convertDataGxy.subList(0, 10);
            convertDataGxy = convertDataGxy.subList(10, convertDataGxy.size());
            Log.e("*************", newList.size() + "***" + convertDataGxy.size() + "*******************");
        } else {
            newList = convertDataGxy;
            convertDataGxy = null;
        }

        UploadDataBean udb3 = new UploadDataBean("高血压",
                JX_UploadData.TYPE_HYPERTENSION, "HyperJson",
                "addHypertension", "gxy", newList);
        list.add(udb3);
        showProgressDialog(udb3.getDataName() + "数据正在上传中，请稍候...");
        GlobalConts.UPLOAD_TYPE = "/CD_HYPERTENSIONFOLLOWUP";
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 健康体检
     */
    public void updaTaJKTJ() {
        List list = new ArrayList<>();
        // 健康体检
        List<HealthCheck> newList = null;

        if (convertDataJktj.size() > 10) {
            newList = convertDataJktj.subList(0, 10);
            convertDataJktj = convertDataJktj.subList(10, convertDataJktj.size());
            Log.e("*************", newList.size() + "***" + convertDataJktj.size() + "*******************");
        } else {
            newList = convertDataJktj;
            convertDataJktj = null;
        }

        UploadDataBean udb4 = new UploadDataBean("健康体检",
                JX_UploadData.TYPE_HEALTHCHECK, "JktjAllJson",
                "addJktjAll", "jktj", newList);
        list.add(udb4);
        showProgressDialog(udb4.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 老年人中医药
     */
    public void upDataLNRZYY() {
        List list = new ArrayList<>();
        // 老年人中医药
        List<OldPhysique> newList = null;

        if (convertDataLnrzyy.size() > 10) {
            newList = convertDataLnrzyy.subList(0, 10);
            convertDataLnrzyy = convertDataLnrzyy.subList(10, convertDataLnrzyy.size());
            Log.e("*************", newList.size() + "***" + convertDataLnrzyy.size() + "*******************");
        } else {
            newList = convertDataLnrzyy;
            convertDataLnrzyy = null;
        }

        UploadDataBean udb5 = new UploadDataBean("老年人中医药",
                JX_UploadData.TYPE_OLD_PHYSIQUE,
                "OldPhysiqueJson", "addOldPhysique", "oldPhysic",
                newList);
        list.add(udb5);
        showProgressDialog(udb5.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 老年人自理能力
     */
    public void upDataLNRZLNL() {
        List list = new ArrayList<>();
        // 老年人自理能力
        List<OldSelfHelp> newList = null;

        if (convertDataLnrzlnl.size() > 10) {
            newList = convertDataLnrzlnl.subList(0, 10);
            convertDataLnrzlnl = convertDataLnrzlnl.subList(10, convertDataLnrzlnl.size());
            Log.e("*************", newList.size() + "***" + convertDataLnrzlnl.size() + "*******************");
        } else {
            newList = convertDataLnrzlnl;
            convertDataLnrzlnl = null;
        }

        UploadDataBean udb6 = new UploadDataBean("老年人自理能力",
                JX_UploadData.TYPE_OLD_SELF_HELP,
                "OlsSelfHelpJson", "addOldSelfHelp", "oldself",
                newList);
        list.add(udb6);
        showProgressDialog(udb6.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 新生儿访视
     */
    public void upDataXSEFS() {
        List list = new ArrayList<>();
        // 新生儿访视
        List<ChildhealthNeonate> newList = null;

        if (convertDataXSRFS.size() > 10) {
            newList = convertDataXSRFS.subList(0, 10);
            convertDataXSRFS = convertDataXSRFS.subList(10, convertDataXSRFS.size());
            Log.e("*************", newList.size() + "***" + convertDataXSRFS.size() + "*******************");
        } else {
            newList = convertDataXSRFS;
            convertDataXSRFS = null;
        }

        UploadDataBean udb10 = new UploadDataBean("新生儿访视",
                JX_UploadData.TYPE_XSRFS,
                "jsonkey", "addChildhealthNeonate", "",
                newList);
        list.add(udb10);
        showProgressDialog(udb10.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 满月龄儿童访视
     */
    public void upDataMYLET() {
        List list = new ArrayList<>();
        // 满月龄儿童访视
        List<ChildWithOneYearOld> newList = null;

        if (convertDataOneMonth.size() > 10) {
            newList = convertDataOneMonth.subList(0, 10);
            convertDataOneMonth = convertDataOneMonth.subList(10, convertDataOneMonth.size());
            Log.e("*************", newList.size() + "***" + convertDataOneMonth.size() + "*******************");
        } else {
            newList = convertDataOneMonth;
            convertDataOneMonth = null;
        }

        UploadDataBean udb11 = new UploadDataBean("满月龄儿童访视",
                JX_UploadData.TYPE_XSRFS,
                "jsonkey", "addChildhealthChildren", "",
                newList);
        list.add(udb11);
        showProgressDialog(udb11.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 三月龄儿童访视
     */
    public void upDataSYLET() {
        List list = new ArrayList<>();
        // 三月龄儿童访视
        List<ChildWithOneYearOld> newList = null;

        if (convertDataThreeMonth.size() > 10) {
            newList = convertDataThreeMonth.subList(0, 10);
            convertDataThreeMonth = convertDataThreeMonth.subList(10, convertDataThreeMonth.size());
            Log.e("*************", newList.size() + "***" + convertDataThreeMonth.size() + "*******************");
        } else {
            newList = convertDataThreeMonth;
            convertDataThreeMonth = null;
        }

        UploadDataBean udb12 = new UploadDataBean("三月龄儿童访视",
                JX_UploadData.TYPE_THREEMONTH,
                "jsonkey", "addChildhealthChildren", "",
                newList);
        list.add(udb12);
        showProgressDialog(udb12.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 六月龄儿童访视
     */
    public void upDataLYLET() {
        List list = new ArrayList<>();
        // 六月龄儿童访视
        List<ChildWithOneYearOld> newList = null;

        if (convertDataSixMonth.size() > 10) {
            newList = convertDataSixMonth.subList(0, 10);
            convertDataSixMonth = convertDataSixMonth.subList(10, convertDataSixMonth.size());
            Log.e("*************", newList.size() + "***" + convertDataSixMonth.size() + "*******************");
        } else {
            newList = convertDataSixMonth;
            convertDataSixMonth = null;
        }

        UploadDataBean udb12 = new UploadDataBean("六月龄儿童访视",
                JX_UploadData.TYPE_SIXMONTH,
                "jsonkey", "addChildhealthChildren", "",
                newList);
        list.add(udb12);
        showProgressDialog(udb12.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 八月龄儿童访视
     */
    public void upDataBYLET() {
        List list = new ArrayList<>();
        // 八月龄儿童访视
        List<ChildWithOneYearOld> newList = null;

        if (convertData8Month.size() > 10) {
            newList = convertData8Month.subList(0, 10);
            convertData8Month = convertData8Month.subList(10, convertData8Month.size());
            Log.e("*************", newList.size() + "***" + convertData8Month.size() + "*******************");
        } else {
            newList = convertData8Month;
            convertData8Month = null;
        }

        UploadDataBean udb12 = new UploadDataBean("8月龄儿童访视",
                JX_UploadData.TYPE_EIGHTMONTH,
                "jsonkey", "addChildhealthChildren", "",
                newList);
        list.add(udb12);
        showProgressDialog(udb12.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 签约用户
     */
    public void upDataQYYH() {

        List list = new ArrayList<>();
        // 签约用户
        List<JTYSCustomerDoctorCont> newList = null;

        if (conts.size() > 10) {
            newList = conts.subList(0, 10);
            conts = conts.subList(10, conts.size());
            Log.e("*************", newList.size() + "***" + conts.size() + "*******************");
        } else {
            newList = conts;
            conts = null;
        }

        UploadDataBean udb1 = new UploadDataBean("签约用户", JX_UploadData.TYPE_QYYH, "jsonQYStr",
                "addCustomerDoctorCont", "", newList);
        list.add(udb1);
        showProgressDialog(udb1.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }

    /**
     * 服务满意度
     */
    public void upDataFWMYD() {

        List list = new ArrayList<>();
        // 服务满意度
        List<JTYSDoctorEvaluateBean> newList = null;

        if (evaluates.size() > 10) {
            newList = evaluates.subList(0, 10);
            evaluates = evaluates.subList(10, evaluates.size());
            Log.e("*************", newList.size() + "***" + evaluates.size() + "*******************");
        } else {
            newList = evaluates;
            evaluates = null;
        }

        UploadDataBean udb2 = new UploadDataBean("服务满意度用户", JX_UploadData.TYPE_FWMYD, "ServiceSatisJson",
                "addServiceSatis", "", newList);
        list.add(udb2);
        showProgressDialog(udb2.getDataName() + "数据正在上传中，请稍候...");
        UploadDatas uld = new UploadDatas(DataDownLoadMainActivity.this, list);
        uld.uploadDatas();
    }


    public void getHandler() {
        Manager.getInstance().setHandler(handler);
    }

    /**
     * 检查网络状态和Token是否存在
     */
    private void CheckToken() {
        if (SPUtil.getIsShiYong(mContext)) {
            showTextDialog("试用状态下无法进行数据上传!");
            return;
        }
        if (TextUtils.isEmpty(SPUtil.getToken(mContext))) {
            getToken();
        }
    }

    /**
     * 没有token值时重新获取token值
     */
    private void getToken() {

        try {
            new ZCMWebService(mContext) {

                @Override
                public void start(String message) {
                    super.start(message);
                }

                @Override
                public void onSynchronize(String message, int syncCount, int dataSize) {
                    super.onSynchronize(message, syncCount, dataSize);
                }

                @Override
                public void complete(final String message) {
                    super.complete(message);
                    cancelProgressDialog();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String token = SPUtil.getToken(mContext);
                            if (TextUtils.isEmpty(token)) {
                                resultDialog.setText("获取token失败,请重试!");
                                resultDialog.showCancleLong();
                                return;
                            }

                        }
                    });
                }

                public void onError(String message) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resultDialog.setText("获取token失败,请检查上传地址是否有误！");
                            resultDialog.showCancleLong();

                        }
                    });
                    return;
                }

                ;
            }.synchrodata(NovaApplication.getImei());
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    resultDialog.setText("获取token失败,请检查上传地址是否有误！");
                    resultDialog.showCancleLong();

                }
            });
            return;
        }

    }

    public void setDatas() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;

            default:
                break;
        }

    }

    // ---------------------------服务项目包-----------------------------------
    Runnable runnable = new Runnable() {

        @Override
        public void run() {// run()在新的线程中运行
            try {
                if (upType.equals(TYPE_FWXMB)) {
                    downloadFwxmb();
                } else if (upType.equals(TYPE_JTQYYH)) {
                    downloadJtqyyh();
                }
                // getRemoteInfo(upType);
                mHandler.sendEmptyMessage(DOWNLOAD_OVER);
            } catch (Exception e) {
                mHandler.sendEmptyMessage(NO_DATA);
                return;
            }
        }
    };

    /**
     * 下载服务项目包
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午7:26:51
     */
    private void downloadFwxmb() {
        try {
            cleanData();
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_FWXM;
            System.out.println("服务项目包" + url + "?" + "type=1&officeId=" + NovaApplication.getJgbh());
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder().add("type", "1")
                    .add("officeId", NovaApplication.getJgbh()).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            System.out.println("服务项目包返回" + result);
            if (!TextUtils.isEmpty(result)) {
                UpDataReturn up = JX_FWXMB.jxFwxmbData(result.toString());
                if (up != null) {
                    if (up.getSize() > 0) {
                        sumSize = up.getSize();
                        successCount = up.getSuccessCount();
                        failCount = up.getFailCount();
                    } else {
                        cleanData();
                    }
                } else {
                    cleanData();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // -----------------------------------------------------------------------

    /**
     * 数据上传【家庭签约用户数据】
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午7:27:43
     */
    private void getDataUp() {
        startCJDA();
        // Thread t3 = new Thread(runnable3);
        // t3.start();
        // try {
        // t3.join();
        // } catch (InterruptedException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

        // new Thread(runnable2).start();
    }

    /**
     * 签约服务
     */

    Runnable runnable1 = new Runnable() {

        @Override
        public void run() {// run()在新的线程中运行
            try {
                okHttp_postFromParameters();
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(0x07);
                return;
            }
        }
    };
    /**
     * 满意度
     */

    Runnable runnable2 = new Runnable() {

        @Override
        public void run() {// run()在新的线程中运行
            try {
                okHttp_postFromParameters_fwmydpj();
            } catch (Exception e) {
                e.printStackTrace();
                // mHandler.sendEmptyMessage(NO_DATA);
                mHandler.sendEmptyMessage(UPLOAD_MEASUREMENT_DATA);
                return;
            }
        }
    };
    /**
     * 创建用户
     */
    Runnable runnable3 = new Runnable() {

        @Override
        public void run() {// run()在新的线程中运行
            try {
                okHttp_postFromParameters_CJYH();
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(UPLOAD_FWMYD);
                return;
            }
        }
    };

    private void downloadJtqyyh() {
        try {
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_XZQYSJ + "/";
            OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
            OkHttpClient okHttpClient = builder.build();
            // OkHttpClient okHttpClient = new OkHttpClient();
            String str_jdrUserName = SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this);
            System.out.println(url + "?" + "qyys=" + str_jdrUserName + "&officeId=" + NovaApplication.getJgbh());
            RequestBody formBody = new FormBody.Builder().add("qyys", str_jdrUserName)
                    .add("officeId", NovaApplication.getJgbh()).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            JSONObject obj;

            String result = response.body().string();
            obj = new JSONObject(result.toString());
            System.out.println("返回的obje" + result);
            if (obj.has("success")) {
                if (obj.getBoolean("success")) {
                    if (obj.has("infor")) {
                        String infor = obj.getString("infor");
                        List<JTYSCustomerDoctorCont> users = new Gson().fromJson(infor,
                                new TypeToken<List<JTYSCustomerDoctorCont>>() {
                                }.getType());
                        List<JTYSCustomerDoctorCont> locDatas = NovaApplication.fdbmanger
                                .findAll(JTYSCustomerDoctorCont.class);
                        Map<String, JTYSCustomerDoctorCont> dataMap = new HashMap<>();
                        for (JTYSCustomerDoctorCont data : locDatas) {
                            dataMap.put(data.getId(), data);
                        }
                        // 2017-03-14 17:40:21
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        for (JTYSCustomerDoctorCont jtys : users) {
                            if (dataMap.containsKey(jtys.getId())) {
                                try {
                                    if (sdf.parse(dataMap.get(jtys.getId()).getUpdatedate())
                                            .after(sdf.parse(dataMap.get(jtys.getId()).getUpdatedate()))) {
                                        NovaApplication.fdbmanger.save(jtys);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                NovaApplication.fdbmanger.save(jtys);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 家庭签约医生数据上传
     */

    private void okHttp_postFromParameters() {
        // new Thread(new Runnable() {
        // @Override
        // public void run() {
        try {
            List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                    "CREATER='" + SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this) + "' AND SIGN!='1'");
            if (conts.size() > 0) {

            } else {
                mHandler.sendEmptyMessage(0x06);
                return;
            }
            String json = new Gson().toJson(conts);

            // 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_SCQYSJ + "/";
            System.out.println("签约用户接口" + url + "?jsonkey=" + json);
            // OkHttpClient okHttpClient = new OkHttpClient();
            OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
            OkHttpClient okHttpClient = builder.build();

            RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            // Log.i(TAG, "接口返回的 的的" + response.body().string());
            String result = response.body().string();
            System.out.println("签约用户接口返回" + result);

            UpDataReturn updata = JX_SJSC.jxJTQYYSData(result);
            if (updata != null) {
                sumSize1 = updata.getSize();
                successCount1 = updata.getSuccessCount();
                failCount1 = updata.getFailCount();
                Log.e("tag", sumSize1 + "sumSize1" + successCount1 + "successCount1" + failCount1 + "failCount1");
            } else {
                cleanData();
            }
            mHandler.sendEmptyMessage(0x06);
        } catch (Exception e) {
            mHandler.sendEmptyMessage(0x07);
            e.printStackTrace();
        }

    }

    /**
     * 服务满意度评价
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:24:17
     */
    private void okHttp_postFromParameters_fwmydpj() {
        try {
            List<JTYSDoctorEvaluateBean> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSDoctorEvaluateBean.class,
                    "CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");
            if (conts.size() > 0) {

            } else {
                mHandler.sendEmptyMessage(UPLOAD_MEASUREMENT_DATA);
                return;
            }
            String json = new Gson().toJson(conts);

            // 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_FWMYDPJ + "/";
            System.out.println("服务满意度" + url + "?jsonkey=" + json);

            OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
            OkHttpClient okHttpClient = builder.build();
            // OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            UpDataReturn updata = JX_SJSC.jxFwmydData(response.body().string());
            if (updata != null) {
                sumSize2 = updata.getSize();
                successCount2 = updata.getSuccessCount();
                failCount2 = updata.getFailCount();
                Log.e("tag", sumSize2 + "sumSize2" + successCount2 + "successCount2" + failCount2 + "failCount2");
            } else {
                cleanData();
            }
            mHandler.sendEmptyMessage(UPLOAD_MEASUREMENT_DATA);
        } catch (Exception e) {
            mHandler.sendEmptyMessage(UPLOAD_MEASUREMENT_DATA);
            e.printStackTrace();
        }

    }

    /**
     * 创建用户上传
     *
     * @author 王婷婷
     * @date 2017年6月5日 下午2:24:17
     */
    private void okHttp_postFromParameters_CJYH() {
        try {
            List<JTYS_BASEINFO> conts = NovaApplication.fdbmanger.findAllByWhere(JTYS_BASEINFO.class,
                    "CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");

            if (conts.size() > 0) {

            } else {
                mHandler.sendEmptyMessage(UPLOAD_FUMYD2);
                return;
            }
            String json = new Gson().toJson(conts);
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_CJDA_LIST;
            System.out.println(url + "?jsonkey=" + json);
            OkHttpClient okHttpClient = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            // Log.i(TAG, "接口返回的 的的" + response.body().string());
            UpDataReturn updata = JX_SJSC.jxCJYHData(response.body().string());
            if (updata != null) {
                sumSize0 = updata.getSize();
                successCount0 = updata.getSuccessCount();
                failCount0 = updata.getFailCount();
                errorMsg0 = updata.getErrMsg();
                failCountYcz0 = updata.getFailCountYcz();
            } else {
                cleanData();
            }
            mHandler.sendEmptyMessage(UPLOAD_FUMYD2);
        } catch (Exception e) {
            mHandler.sendEmptyMessage(UPLOAD_FWMYD);
            e.printStackTrace();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {// 此方法在ui线程运行
            switch (msg.what) {
                case DOWNLOAD_OVER:
                    if (resultDialog == null) {
                        resultDialog = new ResultTextDialog(DataDownLoadMainActivity.this);
                    }
                    resultDialog.setText("下载数据总共" + sumSize + "条,保存成功" + successCount + "条,保存失败" + failCount + "条。");
                    resultDialog.showCancleLong();
                    break;
                case UPLOAD_FWMYD:
                    startQYys();
                    break;
                case NO_DATA:
                    if (resultDialog == null) {
                        resultDialog = new ResultTextDialog(DataDownLoadMainActivity.this);
                    }
                    resultDialog.setText("暂无数据上传");
                    resultDialog.showCancleShort();
                    break;
                case SHOW_UPLOAD_RESULT:
                    showUpLoadDataResult();
                    break;
                case UPLOAD_FUMYD2:
                    startQYys();
                    break;
                case 0x06:// 666
                    startFwmyd();
                    break;
                case 0x07:// 666
                    startFwmyd();
                    break;
                case UPLOAD_MEASUREMENT_DATA:
                    startMeasurementData();
                    break;
            }
        }

    };

    private void cleanData() {
        sumSize = 0;
        successCount = 0;
        failCount = 0;

        sumSize0 = 0;
        successCount0 = 0;
        failCount0 = 0;
        errorMsg0 = "";
        failCountYcz0 = 0;

        sumSize1 = 0;
        successCount1 = 0;
        failCount1 = 0;

        sumSize2 = 0;
        successCount2 = 0;
        failCount2 = 0;

        sumSize3 = 0;
        successCount3 = 0;
        failCount3 = 0;
    }

    @Override
    public void setListeners() {

    }

    /**
     * 测量数据历史上传
     */
    private void startMeasurementData() {

        new Thread(runnable4).start();

    }

    Runnable runnable4 = new Runnable() {

        @Override
        public void run() {

            okHttp_postFromParameters_MeasurementData();
        }
    };

    protected void okHttp_postFromParameters_MeasurementData() {
        try {
            List<MeasurementData> dataList = new MeasurementData().converData().getDataList();
            if (dataList.size() == 0) {
                mHandler.sendEmptyMessage(SHOW_UPLOAD_RESULT);
                return;
            }

            String json = new Gson().toJson(dataList);

            // 请求完整url：http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
            String url = GlobalContsJTYS.getUrlPost_JTYS() + GetPostJTYS.URL_JTYS_MEASURE_DATA;// TODO:需要修改
            // String url = "" + GetPostJTYS.URL_JTYS_MEASURE_DATA;// TODO:需要修改
            System.out.println("测量数据接口" + url + "?jsonkey=" + json);
            // OkHttpClient okHttpClient = new OkHttpClient();
            OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(100, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS);
            OkHttpClient okHttpClient = builder.build();

            RequestBody formBody = new FormBody.Builder().add("jsonkey", json).build();
            Request request = new Request.Builder().url(url).post(formBody).build();
            okhttp3.Response response = okHttpClient.newCall(request).execute();
            // Log.i(TAG, "接口返回的 的的" + response.body().string());
            String result = response.body().string();
            System.out.println("测量数据接口返回" + result);

            UpDataReturn updata = JX_SJSC.jxMeasureDataHistoryData(result);
            if (updata != null) {
                sumSize3 = updata.getSize();
                successCount3 = updata.getSuccessCount();
                failCount3 = updata.getFailCount();
                Log.e("tag", sumSize3 + "sumSize3" + successCount3 + "successCount3" + failCount3 + "failCount3");
            } else {
                cleanData();
            }
            mHandler.sendEmptyMessage(SHOW_UPLOAD_RESULT);
        } catch (Exception e) {
            mHandler.sendEmptyMessage(SHOW_UPLOAD_RESULT);
            e.printStackTrace();
        }

    }

    /**
     * 服务满意度数据上传
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午7:50:28
     */
    private void startFwmyd() {

        List<JTYSDoctorEvaluateBean> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSDoctorEvaluateBean.class,
                "CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");
        if (conts.size() == 0) {
            // showUpLoadDataResult();
            startMeasurementData();
            return;
        }

        new Thread(runnable2).start();
    }

    /**
     * 服务满意度数据上传
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午7:50:28
     */
    private void startQYys() {
        List<JTYSCustomerDoctorCont> conts = NovaApplication.fdbmanger.findAllByWhere(JTYSCustomerDoctorCont.class,
                "CREATER='" + SPUtil.getstr_jdrusername(DataDownLoadMainActivity.this) + "' AND SIGN!='1'");

        if (conts.size() == 0) {
            startFwmyd();
            return;
        }

        new Thread(runnable1).start();
    }

    /**
     * 创建档案
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午7:50:28
     */
    private void startCJDA() {
        List<JTYS_BASEINFO> conts = NovaApplication.fdbmanger.findAllByWhere(JTYS_BASEINFO.class,
                "CREATER='" + NovaApplication.getJgrno() + "' AND SIGN ='0'");

        if (conts.size() == 0) {
            startQYys();
            return;
        }

        new Thread(runnable3).start();
    }

    /**
     * 显示数据返回结果
     *
     * @author 王婷婷
     * @date 2017年7月17日 下午8:04:03
     */
    private void showUpLoadDataResult() {
        if (resultDialog == null) {
            resultDialog = new ResultTextDialog(DataDownLoadMainActivity.this);
        }
        if (sumSize0 != 0 || sumSize1 != 0 || sumSize2 != 0 || sumSize3 != 0) {

            String str_jdyhDataReturn = "建档用户  上传数据总共" + sumSize0 + "条,上传成功" + successCount0 + "条,上传失败" + failCount0
                    + "条,已存在 " + failCountYcz0 + "条。" + (TextUtils.isEmpty(errorMsg0) ? "" : "\n" + errorMsg0);
            resultDialog.setText(str_jdyhDataReturn + "\n" + "签约用户  上传数据总共" + sumSize1 + "条,上传成功" + successCount1
                    + "条,上传失败" + failCount1 + "条。\n" + "服务满意度  上传数据总共" + sumSize2 + "条,上传成功" + successCount2 + "条,上传失败"
                    + failCount2 + "条。\n" + "测量数据  上传数据总共" + sumSize3 + "条,上传成功" + successCount3 + "条,上传失败" + failCount3
                    + "条。");
            resultDialog.showCancleLong();
        } else {
            resultDialog.setText("暂无数据上传");
            resultDialog.showCancleShort();
        }
    }
}
